package com.example.mobifin_busticket;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.controller.databasemanager.DatabaseManager;
import com.example.mobifin_busticket.controller.networkmanager.NetworkManager;


public class MyApplication extends Application {
	private static Context context;
	public static Context activitycontext = null;
	public static Context appContext = null;
	AppPreferences preferences;
	Handler handler = new Handler();
	public static UserInfo userInfo;
	private static DatabaseManager databaseManagerInstance;
	// AppPreferences preferences;
	// private UserInfo userInfo;
	// HttpConn httpConn = new HttpConn();
	private static ProgressDialog pd;

	static public boolean uiInForeground = false;

	public void onCreate() {
		super.onCreate();
		MyApplication.context = getApplicationContext();
		loadManagers();
	}

	public static Context getAppContext() {
		return MyApplication.context;
	}

	public static boolean checkConnectivity(Context ctx) {
		ConnectivityManager connectivityManager = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		NetworkInfo activeWifiInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		boolean isconnected = (activeNetInfo != null && activeNetInfo
				.isConnectedOrConnecting())
				|| (activeWifiInfo != null && activeWifiInfo
						.isConnectedOrConnecting());

		return isconnected;
	}

	public static void showProgressDialog(Context context1, String strTag) {
		pd = ProgressDialog.show(context1, null, strTag, true);
		// pd.setContentView(R.layout.progressbusticket);
		// TextView tv = (TextView) pd.findViewById(R.id.tvMessage);
		// tv.setText(strTag);
		// Typeface tf = Typeface.createFromAsset(tv.getContext().getAssets(),
		// "Roboto-Light.ttf");
		//
		// tv.setTypeface(tf);
		//
		// Window window = pd.getWindow();
		// window.setLayout(LayoutParams.FILL_PARENT,
		// LayoutParams.WRAP_CONTENT);
	}

	public ProgressDialog getPD() {
		return pd;
	}

	// public static void showProgressDialog(Context context1, String title,
	// String msg) {
	// pd = ProgressDialog.show(context1, null, "", true);
	// pd.setContentView(R.layout.progressbusticket);
	// TextView tv = (TextView) pd.findViewById(R.id.tvMessage);
	// tv.setText(msg);
	// TextView tvTitle = (TextView) pd.findViewById(R.id.tvSearchfor);
	// tvTitle.setText(title);
	//
	// Window window = pd.getWindow();
	// window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
	// }

	public static void dismissProgressDialog() {
		if (pd.isShowing()) {
			pd.dismiss();
		}
	}

	public static ProgressDialog getPd() {
		return pd;
	}

	public boolean getSessionId(Context contex) throws JSONException,
			NoSuchAlgorithmException, UnsupportedEncodingException {
		boolean isSessionGenerated = false;
		appContext = context;
		userInfo = AppData.getUserInfo();
		preferences = new AppPreferences(context);
		Calendar cal = Calendar.getInstance();

		cal.setTime(new Date());

		JSONObject object = new JSONObject();
		object.put("MethodName", "DstGenerateSessionID");
		object.put("RequestUniqueID", cal.getTimeInMillis());

		String response = null;
		try {
			NetworkManager networkManger = NetworkManager.getInstance();
			response = networkManger.makeHttpConnection(context,
					AppData.AgenthostURL, object);

			System.out.println("Result:" + response);

			final JSONObject jsonObject = new JSONObject(response);

			if (jsonObject.getString("ResponseCode").equals("000")) {
				String sessionId = jsonObject.getString("SessionID");
				Log.i("SessionId", sessionId);
				isSessionGenerated = true;
				preferences.setSessionId(sessionId);
				AppData.setSessionId(sessionId);
			} else {
				isSessionGenerated = false;
				handler.post(new Runnable() {
					public void run() {
						try {
							Toast.makeText(
									appContext,
									jsonObject.getString("ResponseDescription"),
									Toast.LENGTH_SHORT).show();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
			isSessionGenerated = false;
		}

		return isSessionGenerated;
	}

	public static DatabaseManager getDatabaseManagerInstance() {
		return databaseManagerInstance;
	}

	public static void closeDb() {
		databaseManagerInstance.close();
	}

	public void loadManagers() {
		// Load Managers
		// BusTicketManagaer busTicketManagaer =
		// BusTicketManagaer.getInstance();
		// busTicketManagaer.init();
		// databaseManagerInstance = new
		// DatabaseManager(getApplicationContext());
		BusTicketManagaer busTicketManagaer = BusTicketManagaer.getInstance();
		busTicketManagaer.init();
		databaseManagerInstance = new DatabaseManager(getApplicationContext());
	}

}
